package com.sunthy.mall.controller.admin;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.sunthy.mall.model.admin.Result;
import com.sunthy.mall.model.admin.bo.goods.AddGoodsBO;
import com.sunthy.mall.model.admin.bo.goods.GoodsDeleteSpecBo;
import com.sunthy.mall.model.admin.bo.goods.GoodsUpdateBo;
import com.sunthy.mall.model.admin.bo.goods.GoodsUpdateSpecBo;
import com.sunthy.mall.model.admin.bo.reply.ReplyBo;
import com.sunthy.mall.model.admin.pojo.goods.Type;
import com.sunthy.mall.model.admin.vo.goods.AllGoodsInfoVo;
import com.sunthy.mall.model.admin.vo.goods.AllGoodsVo;
import com.sunthy.mall.model.admin.vo.goods.AllTypeVo;
import com.sunthy.mall.model.admin.vo.reply.AllNoReplyByStateVo;
import com.sunthy.mall.model.admin.vo.reply.AllReplyByStateVo;
import com.sunthy.mall.service.admin.goods.GoodsService;
import com.sunthy.mall.service.admin.goods.GoodsServiceImpl;
import com.sunthy.mall.utils.FileUploadUtils;
import com.sunthy.mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {
    private Gson gson = new Gson();

    private GoodsService goodsService = new GoodsServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if ("/addType".equals(pathInfo)) {

            // 添加商品类目
            addType(request, response);

        } else if ("/imgUpload".equals(pathInfo)) {

            // 上传图片
            imgUpload(request, response);

        } else if ("/addGoods".equals(pathInfo)) {

            // 添加商品
            addGoods(request, response);

        } else if ("/updateGoods".equals(pathInfo)) {

            // 修改商品
            updateGoods(request, response);

        } else if ("/addSpec".equals(pathInfo)) {

            // 添加规格
            addSpec(request, response);

        } else if ("/deleteSpec".equals(pathInfo)) {

            // 删除规格
            deleteSpec(request, response);

        } else if ("/reply".equals(pathInfo)) {

            // 回复留言
            reply(request, response);

        }
    }

    /********
     * 回复留言的逻辑
     *      1.接受请求参数
     *      2.更改数据库
     *      3.返回结果
     * @param request
     * @param response
     */
    private void reply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        ReplyBo replyBo = gson.fromJson(requestBody, ReplyBo.class);
        // 校验参数
        if ("".equals(replyBo.getContent())) {
            // 空白留言 返回错误提醒
            response.getWriter().println(gson.toJson(Result.error("空回复,请用心回复每一条留言")));
            return;
        }
        // 更改数据
        int code = goodsService.replyByAdmin(replyBo);
        // 返回结果
        if (code == 0) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("异常")));
    }

    /**
     * 删除规格的逻辑:
     * 1.获取请求参数
     * 2.删除spec
     * 3.返回参数
     *
     * @param request
     * @param response
     */
    private void deleteSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        GoodsDeleteSpecBo goodsDeleteSpecBo = gson.fromJson(requestBody, GoodsDeleteSpecBo.class);
        // 删除spec
        int code = goodsService.deleteSpec(goodsDeleteSpecBo);
        // 返回结果
        if (code == 0) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("删除错误")));
    }

    /**
     * 修改商品的逻辑:
     * 1.获取请求参数
     * 2.去数据库中修改数据
     * 3.返回结果
     *
     * @param request
     * @param response
     */
    private void updateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        // 校验请求
        GoodsUpdateBo goodsUpdateBo = null;
        try {
            goodsUpdateBo = gson.fromJson(requestBody, GoodsUpdateBo.class);
        } catch (JsonSyntaxException e) {
            response.getWriter().println(gson.toJson(Result.error("参数不合法")));
            return;
        }
        // 去数据库中需改数据
        int code = goodsService.updateGoods(goodsUpdateBo);
        // 返回信息
        if (code == 0) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("修改错误")));
    }

    /**
     * 添加规格的逻辑：
     * 1.获取请求参数
     * 2.添加到数据库
     * 3.返回结果
     *
     * @param request
     * @param response
     */
    private void addSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        GoodsUpdateSpecBo goodsUpdateSpecBo = null;
        try {
            goodsUpdateSpecBo = gson.fromJson(requestBody, GoodsUpdateSpecBo.class);
        } catch (JsonSyntaxException e) {
            response.getWriter().println(gson.toJson(Result.error("参数异常")));
            return;
        }
        // 添加到数据库中
        int code = goodsService.addSpecBeforeAddGoods(goodsUpdateSpecBo);
        if (code == 0) {// 成功
            response.getWriter().println(gson.toJson(Result.ok(goodsUpdateSpecBo)));
            return;
        }// 失败
        response.getWriter().println(gson.toJson(Result.error("不可添加重复的规格")));
    }

    /**
     * 添加商品的逻辑：
     * 1.获取请求参数
     * 2.添加数据
     * 3.返回结果
     *
     * @param request
     * @param response
     */
    private void addGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数   请求体  json字符串
        String requestBody = HttpUtils.getRequestBody(request);
        AddGoodsBO addGoodsBO = null;
        // 校验参数
        try {
            addGoodsBO = gson.fromJson(requestBody, AddGoodsBO.class);
        } catch (JsonSyntaxException e) {
            response.getWriter().println(gson.toJson(Result.error("参数不合法")));
            return;
        }
        // 添加数据
        goodsService.addGoods(addGoodsBO);
        // 返回结果
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * img上传的逻辑: 直接调用工具类
     * 1.获取请求参数
     * 2.将文件上传
     * 3.返回结果
     *
     * @param request
     * @param response
     */
    private void imgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = FileUploadUtils.parseRequest(request);
        String file = (String) map.get("file");
        // 返回结果
        response.getWriter().println(gson.toJson(Result.ok(file)));
    }

    /**
     * 添加类目的逻辑：
     * 1.拿到要添加商品的名称
     * 2.添加到数据库
     * 3.返回结果
     *
     * @param request
     * @param response
     */
    private void addType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String requestBody = HttpUtils.getRequestBody(request);
        Type type = gson.fromJson(requestBody, Type.class);
        if ("".equals(type.getName())) {
            // name 为"" 不符合逻辑
            response.getWriter().println(gson.toJson(Result.error("名字不合法")));
            return;
        }
        // 添加到数据库中
        int code = goodsService.addType(type);
        // 返回结果
        if (code != 0) {
            // 失败 名字错误
            response.getWriter().println(gson.toJson(Result.error("名字重复!换个名字吧")));
            return;
        }
        // 成功
        response.getWriter().println(gson.toJson(Result.ok()));
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String replace = requestURI.replace(request.getContextPath() + "/api/admin/goods/", "");
        if ("getType".equals(replace)) {

            // 获取商品类目
            getType(request, response);

        } else if ("getGoodsByType".equals(replace)) {

            // 获取同类目下的商品
            getGoodsByType(request, response);

        } else if ("deleteType".equals(replace)) {

            // 删除商品类目
            deleteType(request, response);

        } else if ("deleteGoods".equals(replace)) {

            // 删除商品
            deleteGoods(request, response);

        } else if ("getGoodsInfo".equals(replace)) {

            // 回显商品品
            getGoodsInfo(request, response);

        } else if ("noReplyMsg".equals(replace)) {

            // 获取未回复留言
            noReplyMsg(request, response);

        } else if ("repliedMsg".equals(replace)) {

            // 获取已回复留言
            repliedMsg(request, response);

        }

    }

    /****************
     * 获取已回复留言的逻辑
     *        1.接收请求参数 (无)
     *        2.查询留言
     *        3.返回数据
     * @param request
     * @param response
     */
    private void repliedMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 查寻留言
        List<AllReplyByStateVo> allReplyByStateVos = goodsService.getReplyMsg();
        // 返回结果
        response.getWriter().println(gson.toJson(Result.ok(allReplyByStateVos)));
    }

    /********************
     * 获取未恢复留言的逻辑
     *        1.接收请求参数 (无)
     *        2.查询留言
     *        3.返回数据
     * @param request
     * @param response
     */
    private void noReplyMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 查询留言
        List<AllNoReplyByStateVo> allNoReplyByStateVos = goodsService.getNoReplyMsg();
        // 返回结果
        response.getWriter().println(gson.toJson(Result.ok(allNoReplyByStateVos)));
    }

    /***********
     * 回显的逻辑：
     *        1.接收请求参数
     *        2.查询数据库
     *        3.返回结果
     * @param request
     * @param response
     */
    private void getGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);
        // 查询数据库
        AllGoodsInfoVo allGoodsInfoVo = goodsService.getGoodsInfoById(id);
        // 返回结果
        response.getWriter().println(gson.toJson(Result.ok(allGoodsInfoVo)));
    }

    /*************
     * 删除商品的逻辑:
     *        1.接收请求参数
     *        2.删除商品
     *        3.返回结果
     * @param request
     * @param response
     */
    private void deleteGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);
        // 删除商品
        int code = goodsService.deleteGoodsById(id);
        // 返回结果
        if (code == 0) {// 成功
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }// 失败
        response.getWriter().println(gson.toJson(Result.error("错误删除")));
    }

    /**
     * 删除类目的逻辑:
     * 1.接收请求参数
     * 2.删除类目
     * 3.返回结果
     *
     * @param request
     * @param response
     */
    private void deleteType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取请求参数
        String typeIdStr = request.getParameter("typeId");
        int typeId = Integer.parseInt(typeIdStr);
        // 删除类目
        int code = goodsService.deleteTypeById(typeId);
        // 返回结果
        if (code == 0) {// 成功
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        // 失败 异常
        if (code == 500) {
            response.getWriter().println(gson.toJson(Result.error("回收站不可删除!回收站中商品会在30天后自动删除")));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("删除异常")));
    }

    /**
     * 通过商品类目拿到所有商品的逻辑:
     * 1.接收请求参数
     * 2.查询数据库
     * 3.返回结果给客户端
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取请求参数
        String typeIdStr = request.getParameter("typeId");
        int typeId = Integer.parseInt(typeIdStr);
        // 查询数据库
        List<AllGoodsVo> allGoodsList = goodsService.allGoodsByTypeId(typeId);
        // 返回结果
        response.getWriter().println(gson.toJson(Result.ok(allGoodsList)));
    }

    /**
     * 得到商品类目逻辑:
     * 1.查询数据库
     * 2.返回结果给客户端
     *
     * @param request
     * @param response
     */
    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        // 查询数据库
        List<AllTypeVo> allTypeVoList = goodsService.allTypes();
        // 返回结果
        response.getWriter().println(gson.toJson(Result.ok(allTypeVoList)));
    }
}
